package com.contract.management.web;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.apache.commons.collections4.MultiValuedMap;
//import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.contract.management.bean.ReturnMessage;
import com.contract.management.bean.page.PageBean;
import com.contract.management.bean.page.PageResult;
import com.contract.management.bean.page.QueryBean;
import com.contract.management.bean.page.datatables.DtsPageResult;
import com.contract.management.bean.page.datatables.DtsParams;
import com.contract.management.domain.CommJpaRepository;
import com.contract.management.domain.ContFile;
import com.contract.management.domain.Contract;
import com.contract.management.domain.User;
import com.contract.management.domain.WorkflowLog;
import com.contract.management.domain.WorkflowNode;
import com.contract.management.service.ContractService;
import com.contract.management.util.StrUtils;
import com.contract.management.util.WorkFlowUtils;
import com.zhuozhengsoft.pageoffice.BorderStyleType;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;

@Controller
@RequestMapping("/audit")
public class AuditController {

	@Value("${office.basepath}")
	private String basePath;
	
	@Autowired
	private CommJpaRepository repo;
	
	@Autowired
	private ContractService service;
	
	@Autowired
	private RestTemplate restTemplate;
	
	//合同盖章列表
	@RequestMapping(value = "/stamp")
	public String stamp(Model model, HttpSession session, String no, String jfWtr, String user) {
		User audit = (User)session.getAttribute("user");
		List<Map<String, Object>> data = service.getContList1(no, jfWtr, user, null, audit, 7);
		for (Map<String, Object> map : data) {
			StringBuilder option = new StringBuilder("<a href = 'javascript:;' onclick='stamp_cont(");
			option.append(map.get("id")).append(")'>盖章</a>");
			map.put("option", option.toString());
		}
		model.addAttribute("rows", data);
		model.addAttribute("url", "audit/flow/stamp");
		model.addAttribute("title", "合同盖章");
		
		model.addAttribute("no", no);
		model.addAttribute("jfWtr", jfWtr);
		model.addAttribute("user", user);
		return "stamp_list";
	}
	
	//合同盖章提交（人工）
	@RequestMapping(value = "/stamp/rg", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public ReturnMessage rgStampSubmit(Model model, HttpSession session, int id) {
		Contract ct = repo.find(Contract.class, id);
		if(ct == null) return new ReturnMessage(false, "该合同不存在");
		User user = (User)session.getAttribute("user");
		if(ct.getAudit().getId() != (int)user.getId()) return new ReturnMessage(false, "操作错误");
		if(ct.getCurNode().getId() != 7)  return new ReturnMessage(false, "操作错误");
		
		WorkflowNode nextNode = WorkFlowUtils.getNextNode(ct, repo);
		ct.setCurNode(nextNode);
		ct.setNodeInfo(nextNode.getName());
		ct.setNextOper("");
		ct.setAudit(ct.getUser());
		repo.merge(ct);
		
		WorkflowLog log = new WorkflowLog();
		log.setCt(ct);
		log.setUser(user);
		log.setSpjg(1);
		log.setSpsm("人工盖章完成，下一步上传合同资料");
		log.setCreateTime(new Date());
		repo.persist(log);
		
		return new ReturnMessage(true);
	}
	
	//一键盖章多个合同（人工）
	@RequestMapping(value = "/stamp/rgall", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public ReturnMessage rgAllStampSubmit(Model model, HttpSession session, @RequestParam("ids[]") Integer[] ids) {
		for (Integer id : ids) {
			Contract ct = repo.find(Contract.class, id);
			if(ct == null) return new ReturnMessage(false, "该合同不存在");
			User user = (User)session.getAttribute("user");
			if(ct.getAudit().getId() != (int)user.getId()) return new ReturnMessage(false, "操作错误");
			if(ct.getCurNode().getId() != 7)  return new ReturnMessage(false, "操作错误");
			
			WorkflowNode nextNode = WorkFlowUtils.getNextNode(ct, repo);
			ct.setCurNode(nextNode);
			ct.setNodeInfo(nextNode.getName());
			ct.setNextOper("");
			ct.setAudit(ct.getUser());
			repo.merge(ct);
			
			WorkflowLog log = new WorkflowLog();
			log.setCt(ct);
			log.setUser(user);
			log.setSpjg(1);
			log.setSpsm("人工盖章完成，下一步上传合同资料");
			log.setCreateTime(new Date());
			repo.persist(log);
		}
		return new ReturnMessage(true);
	}
	
	//合同盖章（电子）
	@RequestMapping(value = "/stamp/{id}", method = RequestMethod.GET)
	public String stampDz(HttpServletRequest request, Model model, HttpSession session, @PathVariable int id) {
		String error = null;
		Contract ct = repo.find(Contract.class, id);
		if(ct == null) error = "该合同不存在";
		User user = (User)session.getAttribute("user");
		if(ct.getAudit().getId() != (int)user.getId()) error = "操作错误";
		if(ct.getCurNode().getId() != 7) error = "操作错误";
		
		if(error != null) {
			model.addAttribute("text", error);
			return "show_error_message";
		}
		
		String filePath = basePath + "contracts/" + ct.getDocName();
		File file = new File(filePath);
		if(!file.exists()) {
			model.addAttribute("text", "电子合同不存在");
			return "show_error_message";
		}

		PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
		poCtrl.setServerPage("/poserver.zz");
		
		poCtrl.addCustomToolButton("全屏/还原", "fullScreen", 4);
		poCtrl.addCustomToolButton("隐藏/显示工具栏", "office_toolbar", 0);
		poCtrl.addCustomToolButton("-", "", 0);
		poCtrl.addCustomToolButton("加盖印章", "add_seal()", 2);
		poCtrl.addCustomToolButton("保存","save",1);
		poCtrl.setSaveFilePage("/audit/stamp/dz");
		poCtrl.setTitlebar(false);
		poCtrl.setMenubar(false);
		poCtrl.setBorderStyle(BorderStyleType.BorderThin);
		poCtrl.webOpen("/contracts/" + ct.getDocName(), OpenModeType.docReadOnly, "");
		model.addAttribute("pageoffice", poCtrl.getHtmlCode("page_office"));
		model.addAttribute("id", id);
		return "stamp_dz";
	}
	//合同盖章提交（电子）
	@RequestMapping(value = "/stamp/dz")
	@Transactional
	public void dzStampSubmit(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		User user = (User)session.getAttribute("user");
		FileSaver fs = new FileSaver(request,response);
		if (fs.getFormField("id") != null) {
			int id = Integer.parseInt(fs.getFormField("id"));
			Contract ct = repo.find(Contract.class, id);
			if(ct == null) {
				return;
			}
			if(ct.getAudit().getId() != (int)user.getId()) {
				return;
			}
			if(ct.getCurNode().getId() != 7) {
				return;
			}
			String filePath = basePath + "contracts/" + fs.getFileName();
			fs.saveToFile(filePath);
			
			WorkflowNode nextNode = WorkFlowUtils.getNextNode(ct, repo);
			ct.setCurNode(nextNode);
			ct.setNodeInfo(nextNode.getName());
			ct.setNextOper(nextNode.getName());
			ct.setAudit(ct.getUser());
			repo.merge(ct);
			
			WorkflowLog log = new WorkflowLog();
			log.setCt(ct);
			log.setUser(user);
			log.setSpjg(1);
			log.setSpsm("电子盖章完成，下一步上传合同资料");
			log.setCreateTime(new Date());
			repo.persist(log);
		}
		fs.close();
	}
	//合同初审列表
	@RequestMapping("/first")
	public String first(Model model, HttpSession session, String no, String jfWtr, String user) {
		User audit = (User)session.getAttribute("user");
		List<Map<String, Object>> data = service.getContList1(no, jfWtr, user, null, audit, 3, 4, 5);
		for (Map<String, Object> map : data) {
			StringBuilder option = new StringBuilder("<a href = 'javascript:;' onclick='audit_first(");
			option.append(map.get("id")).append(")'>审核</a>");
			map.put("option", option.toString());
		}
		model.addAttribute("rows", data);
		model.addAttribute("url", "first");
		model.addAttribute("title", "合同初审");
		
		model.addAttribute("no", no);
		model.addAttribute("jfWtr", jfWtr);
		model.addAttribute("user", user);
		return "audit_list";
	}
	
	//合同初审
	@RequestMapping("/first/{id}")
	public String auditFirst(HttpServletRequest request, HttpSession session, Model model, @PathVariable int id) {
		Contract ct = repo.find(Contract.class, id);
		User user = (User)session.getAttribute("user");
		ReturnMessage msg = checkAuditFirstRight(ct, user);
		if(!msg.isSuccess()) {
			model.addAttribute("text", msg.getMessage());
			return "show_error_message";
		}

		
		PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
		
		poCtrl.setServerPage("/poserver.zz");
		if(ct.getCurNode().getId() == 3) {
			poCtrl.addCustomToolButton("保存","save",1);
			poCtrl.setSaveFilePage("/audit//contract/save");
		}
		
		poCtrl.addCustomToolButton("全屏/还原", "fullScreen", 4);
		poCtrl.addCustomToolButton("隐藏/显示工具栏", "office_toolbar", 0);
		poCtrl.addCustomToolButton("关闭窗口", "close()", 21);
		
		poCtrl.setTitlebar(false);
		poCtrl.setMenubar(false);
//		poCtrl.setOfficeToolbars(false);
//		poCtrl.setCustomToolbar(false);
		poCtrl.setBorderStyle(BorderStyleType.BorderFlat);
		if(ct.getCurNode().getId() == 3) {
			poCtrl.webOpen("/contracts/" + ct.getDocName(), OpenModeType.docNormalEdit, "");
		} else {
			poCtrl.webOpen("/contracts/" + ct.getDocName(), OpenModeType.docReadOnly, "");
		}
		
		model.addAttribute("pageoffice", poCtrl.getHtmlCode("page_office"));
		
		WorkflowNode nextNode = WorkFlowUtils.getNextNode(ct, repo);
		if(nextNode.getId() == 6) {
			nextNode.setName("下一步打印合同");
		} else {
			nextNode.setName("下一步");
		}
		
		model.addAttribute("next", nextNode);
		model.addAttribute("id", ct.getId());
		model.addAttribute("ct", ct);
		
		//价格审批
		String fzsh = repo.queryOne("select value from SysConfig where key = ?0", "FZSH");
		double fzshbl = Double.parseDouble(fzsh.replace("%", "")) * 0.01;	//副总经理比例
		double fybl = (double)ct.getFyhj() / (double)ct.getZcjg();
		if(fybl <= fzshbl) {
			model.addAttribute("jgsp", true);
			model.addAttribute("jgspStr", "价格审批[为正常报价" + String.format("%.2f", fybl * 100) + "%]");
		} else {
			model.addAttribute("jgsp", false);
		}
		
		//条款审批
		model.addAttribute("tksp", false);
		//上一审批意见
		List<WorkflowLog> logs = repo.query(1, "from WorkflowLog l where l.ct = ?0 order by create_time desc", ct);
		if(logs.size() > 0 && !StrUtils.isEmpty(logs.get(0).getMemo())) {
			model.addAttribute("syspyj", "上一" + logs.get(0).getMemo());
		} else {
			model.addAttribute("syspyj", null);
		}
		
		return "audit_first";
	}
	
	//合同盖章提交（电子）
		@RequestMapping(value = "/contract/save")
		@Transactional
		public void saveContract(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
			FileSaver fs = new FileSaver(request,response);
			String filePath = basePath + "contracts/" + fs.getFileName();
			fs.saveToFile(filePath);
			fs.close();
		}
		
	/**
	 * 合同初审提交
	 *  
	 * @param id		合同ID
	 * @param sp		审批结果 1 同意 0 不同意
	 * @param nextAudit	下一审批人ID
	 * @param spyj		审批意见
	 * @return
	 */
	@RequestMapping(value = "/first/submit", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public ReturnMessage firstSubmit(HttpSession session, int id, int sp, Integer nextOper, String spyj) {
		Contract ct = repo.find(Contract.class, id);
		User user = (User)session.getAttribute("user");
		ReturnMessage msg = checkAuditFirstRight(ct, user);
		if(!msg.isSuccess()) return msg;
		
		String nodeInfo = null;
		WorkflowNode curNode = ct.getCurNode();
		WorkflowNode nextNode = null;
		if(sp == 1) {
			ct.setAudit(nextOper == null ? null : repo.find(User.class, nextOper));
			nextNode = WorkFlowUtils.getNextNode(ct, repo);
			nodeInfo = nextNode.getName();
			ct.setCurNode(nextNode);
			ct.setNextOper("审批");
			ct.setNodeInfo(nodeInfo);
		//未通过修改合同
		} else {
			nextNode = repo.queryOne("from WorkflowNode where id = ?0", 2);
			nodeInfo = nextNode.getName();
			ct.setCurNode(nextNode);
			ct.setNodeInfo(nodeInfo);
			ct.setNextOper("修改");
			ct.setAudit(null);
		}
		repo.merge(ct);
		WorkflowLog log = new WorkflowLog();
		log.setCt(ct);
		log.setUser(user);
		log.setSpjg(sp);
		log.setSpsm(curNode.getName() + (sp == 1 ? "通过" : "未通过") + "，下一步" + nextNode.getName());
		if(!StrUtils.isEmpty(spyj)) log.setMemo("审批意见：" + spyj);
		log.setCreateTime(new Date());
		repo.persist(log);
		
		return new ReturnMessage(true);
	}

	
	//合同复审
	@RequestMapping("/second")
	public String second(Model model, HttpSession session, String no, String jfWtr, String user) {
		User audit = (User)session.getAttribute("user");
		List<Map<String, Object>> data = service.getContList1(no, jfWtr, user, null, audit, 9, 10, 11, 12);
		for (Map<String, Object> map : data) {
			StringBuilder option = new StringBuilder("<a href = 'javascript:;' onclick='audit_second(");
			option.append(map.get("id")).append(")'>审核</a>");
			map.put("option", option.toString());
		}
		model.addAttribute("rows", data);
		model.addAttribute("url", "first");
		model.addAttribute("title", "合同复审");
		
		model.addAttribute("no", no);
		model.addAttribute("jfWtr", jfWtr);
		model.addAttribute("user", user);
		return "audit_list";
	}
	
	//合同复审
	@RequestMapping("/second/{id}")
	public String auditSecond(HttpServletRequest request, HttpSession session, Model model, @PathVariable int id) {
		Contract ct = repo.find(Contract.class, id);
		User user = (User)session.getAttribute("user");
		ReturnMessage msg = checkAuditSecondRight(ct, user);
		if(!msg.isSuccess()) {
			model.addAttribute("text", msg.getMessage());
			return "show_error_message";
		}

		
		PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
		poCtrl.setServerPage("/poserver.zz");
		poCtrl.addCustomToolButton("全屏/还原", "fullScreen", 4);
		poCtrl.addCustomToolButton("隐藏/显示工具栏", "office_toolbar", 0);
		poCtrl.addCustomToolButton("关闭窗口", "close()", 21);
		
		poCtrl.setTitlebar(false);
		poCtrl.setMenubar(false);
//		poCtrl.setOfficeToolbars(false);
//		poCtrl.setCustomToolbar(false);
		poCtrl.setBorderStyle(BorderStyleType.BorderFlat);
		poCtrl.webOpen("/contracts/" + ct.getDocName(), OpenModeType.docReadOnly, "");
		model.addAttribute("pageoffice", poCtrl.getHtmlCode("page_office"));
		
		WorkflowNode nextNode = WorkFlowUtils.getNextNode(ct, repo);
		nextNode.setName("下一步" + nextNode.getName());
		model.addAttribute("next", nextNode);
		model.addAttribute("zjlOpers", repo.query("select new User(id, name) from User u where u.dept.right.id = 1"));
		model.addAttribute("fzOpers", repo.query("select new User(id, name) from User u where u.dept.right.id = 2"));
		model.addAttribute("lcOpers", repo.query("select new User(id, name) from User u where u.dept.right.id = 3"));
		model.addAttribute("ct", ct);
		List<Map<String, Object>> files = repo.query("select new map(id as id, filename as filename, oraName as oraName, type as type) from ContFile  where cont.id = ?0 order by type", id);
		model.addAttribute("files", files);
		
		//上一审批意见
		List<WorkflowLog> logs = repo.query(1, "from WorkflowLog l where l.ct = ?0 order by create_time desc", ct);
		if(logs.size() > 0 && !StrUtils.isEmpty(logs.get(0).getMemo())) {
			model.addAttribute("syspyj", "上一" + logs.get(0).getMemo());
		} else {
			model.addAttribute("syspyj", null);
		}
		
		return "audit_second";
	}
	
	/**
	 * 合同初审提交
	 *  
	 * @param id		合同ID
	 * @param sp		审批结果 1 同意 0 不同意
	 * @param nextAudit	下一审批人ID
	 * @param spyj		审批意见
	 * @return
	 */
	@RequestMapping(value = "/second/submit", method = RequestMethod.POST)
	@Transactional
	public void secondSubmit(HttpServletResponse resp, HttpSession session, int id, int sp, Integer zjlOper, Integer fzOper, Integer lcOper, String spyj, @RequestParam("sp_pic") MultipartFile[] pics) {
		Contract ct = repo.find(Contract.class, id);
		User user = (User)session.getAttribute("user");
		ReturnMessage msg = checkAuditSecondRight(ct, user);
		if(!msg.isSuccess()) {
			try {
				resp.getWriter().write(JSON.toJSONString(msg));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		
		WorkflowNode curNode = ct.getCurNode();
		WorkflowNode nextNode = null;
		User audit = null;
		
		WorkflowLog log = new WorkflowLog();
		if(pics.length > 0) {
			MultipartFile file = pics[0];
			if(file.getSize() > 0 && !"".equals(file.getName().trim())) {
				String oraName = file.getOriginalFilename();
				String filename = StrUtils.getUuidName(file.getOriginalFilename());
				String filePath = basePath + "uploads";
				try {
					file.transferTo(new File(filePath, filename));
					log.setSpPic(filename);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		//审批完成
		if(curNode.getId() == 12) {
			if(sp == 1) {
				
				nextNode = repo.queryOne("from WorkflowNode where id = ?0", 13);
				nextNode.setDesc(nextNode.getName());
				ct.setStatus(1);
				ct.setFinishTime(new Date());
				sendFinishApi(ct);

			} else {
				nextNode = repo.queryOne("from WorkflowNode where id = ?0", 16);
				nextNode.setDesc(curNode.getName() + "不通过，需要补充合同资料");
			}
			ct.setCurNode(nextNode);
			ct.setNodeInfo(nextNode.getName());
			ct.setNextOper(nextNode.getName());
			
			
			log.setCt(ct);
			log.setUser(user);
			log.setSpjg(sp);
			log.setSpsm(nextNode.getDesc());
			if(!StrUtils.isEmpty(spyj)) log.setMemo("审批意见：" + spyj);
			log.setCreateTime(new Date());
			repo.persist(log);
			
		}
		
		if(curNode.getId() == 9 || curNode.getId() == 10 || curNode.getId() == 11) {
			//确认有效，下一步流程部复核
			if(sp == 1) {
				nextNode = repo.queryOne("from WorkflowNode where id = ?0", 12);
				nextNode.setDesc(curNode.getName() + "通过，下一步流程部复核");
				audit = new User(lcOper);
			//无效，返回从新上传
			} else if(sp == 0) {
				nextNode = repo.queryOne("from WorkflowNode where id = ?0", 8);
				nextNode.setDesc(curNode.getName() + "不通过，下一步重新上传合同资料");
			//提交下一审核者
			} else if(sp == 2) {
				if(curNode.getId() == 9) {	//下一步副总复审
					nextNode = repo.queryOne("from WorkflowNode where id = ?0", 10);
					audit = new User(fzOper);
				} else if(curNode.getId() == 10) {	//下一步总经理复审
					nextNode = repo.queryOne("from WorkflowNode where id = ?0", 11);
					audit = new User(zjlOper);
				}
				nextNode.setDesc("合同提交" + nextNode.getName());
			}
			String nextOper = nextNode.getName();
			String nodeInfo = nextNode.getName();			
			ct.setCurNode(nextNode);
			ct.setNodeInfo(nodeInfo);
			ct.setNextOper(nextOper);
			ct.setAudit(audit);
			repo.merge(ct);
			
			log.setCt(ct);
			log.setUser(user);
			log.setSpjg(sp);
			log.setSpsm(nextNode.getDesc());
			if(!StrUtils.isEmpty(spyj)) log.setMemo("审批意见：" + spyj);
			log.setCreateTime(new Date());
			repo.persist(log);
		}
		try {
			resp.getWriter().write(JSON.toJSONString(new ReturnMessage(true)));
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return;
	}
	
	void sendFinishApi(Contract ct) {
		HttpHeaders httpHeaders = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		httpHeaders.setContentType(type);
		httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
		 
		MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
		map.add("contract_num", ct.getNo());
		map.add("area", ct.getArea());
		map.add("user_name", ct.getUser().getName());
		map.add("user_phone", ct.getUser().getTelephone());
		map.add("client_phone", ct.getJfDhhm());
		map.add("client_name", ct.getJfLxr());
		map.add("client_company", ct.getJfWtr());
		map.add("contract_price", ct.getFyhj());
		map.add("first_id", ct.getContSmallClass().getId());
		map.add("first_name", ct.getContSmallClass().getName());
		List<Map<String, Object>> files = repo.query("select new map(c.filename as file_name, c.type as type, c.size as size, c.oraName as ora_name) from ContFile c where c.cont.id = ?0", ct.getId());
		map.add("files", files);
		
		List<Map<String, Object>> product = repo.query("select new map(s.xmmc as xmmc, s.xmlb as xmlb, s.sbzw as sbzw, s.sbyw as sbyw, s.sbtx as sbtx, s.sbzh as sbzh, s.fy as fy, s.zcbj as zcbj, s.wtxmmc as wtxmmc, s.zpmc as zpmc, s.memo as memo) from SbItems s where s.ct.id = ?0", ct.getId());
		map.add("product", product);

		try {
			HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(map), httpHeaders);
//		Object message = restTemplate.postForObject("https://xcx.nanguakefu.com/hetong/createcontract", formEntity, String.class);
			Object message = restTemplate.postForObject("http://hbapi.nanguakefu.com/hetong/createcontract?contract_num="+ct.getNo()+"&area="+ct.getArea()+"&user_name="+ct.getUser().getName()+"&user_phone="+ct.getUser().getTelephone()+"&contract_price="+ct.getFyhj()+"&first_id="+ct.getContSmallClass().getId()+
					"&first_name="+ct.getContSmallClass().getName()+"&client_phone="+ct.getJfDhhm()+"&client_name="+ct.getJfLxr()+"&client_company="+ct.getJfWtr(), formEntity, String.class);
			System.out.println(JSON.toJSONString(message));
		} catch (Exception e){
			
		}
	}
	
	//需要审核/盖章的合同数量
	@RequestMapping("/count")
	@ResponseBody
	public ReturnMessage count(HttpSession session) {
		User user = (User)session.getAttribute("user");
		//合同盖章
		Long htgz = repo.queryOne("select count(*) from Contract c where c.audit = ?0 and c.curNode.id = 7", user);
		//合同初审
		Long htcs = repo.queryOne("select count(*) from Contract c where c.audit = ?0 and c.curNode.id in (?1)", user,  Arrays.asList(3, 4, 5));
		//合同复审
		Long htfs = repo.queryOne("select count(*) from Contract c where c.audit = ?0 and c.curNode.id in (?1)", user, Arrays.asList(9, 10, 11, 12));
		//合同作废
		Long htzf = repo.queryOne("select count(*) from Contract c where c.audit = ?0 and c.curNode.id = ?1", user, 18);

		Map<String, String> map = new HashMap<String, String>() {{
			put("htgz", htgz == 0 ? "" : String.valueOf(htgz));
			put("htcs", htcs == 0 ? "" : String.valueOf(htcs));
			put("htfs", htfs == 0 ? "" : String.valueOf(htfs));
			put("htzf", htzf == 0 ? "" : String.valueOf(htzf));
		}};
		return new ReturnMessage(true, map);
	}
	
	//检查初审权限
	private ReturnMessage checkAuditFirstRight(Contract ct, User user) {
		if(ct == null) {
			return new ReturnMessage(false, "该合同不存在");
		}
		int nodeId = ct.getCurNode().getId();
		if(nodeId != 3 && nodeId != 4 && nodeId != 5) {
			return new ReturnMessage(false, "该合同审核操作错误");
		}
		if(user.getId() != (int)ct.getAudit().getId()) {
			return new ReturnMessage(false, "您没有该合同审核权限");
		}
		String filePath = basePath + "contracts/" + ct.getDocName();
		File file = new File(filePath);
		if(!file.exists()) {
			return new ReturnMessage(false, "该合同电子文档不存在");
		}

		return new ReturnMessage(true);
	}
	
	//检查初审权限
	private ReturnMessage checkAuditSecondRight(Contract ct, User user) {
		if(ct == null) {
			return new ReturnMessage(false, "该合同不存在");
		}
		int nodeId = ct.getCurNode().getId();
		if(nodeId != 9 && nodeId != 10 && nodeId != 11 && nodeId != 12) {
			return new ReturnMessage(false, "该合同审核操作错误");
		}
		if(user.getId() != (int)ct.getAudit().getId()) {
			return new ReturnMessage(false, "您没有该合同审核权限");
		}
		String filePath = basePath + "contracts/" + ct.getDocName();
		File file = new File(filePath);
		if(!file.exists()) {
			return new ReturnMessage(false, "该合同电子文档不存在");
		}
		return new ReturnMessage(true);
	}
	
	//已审核合同
	@RequestMapping("/ysh")
	public String ysh(HttpSession session, Model model) {
		model.addAttribute("ywlxs", repo.query("select new map(s.id as id, concat((CASE s.bigClass.area WHEN 'A' THEN '上海' WHEN 'B' THEN '苏州' WHEN 'C' THEN '成都' END), '-',  s.bigClass.name, '-', s.name) as name) from ContSmallClass s order by s.id"));
		return "ysh_list";
	}
	
	@RequestMapping("/yshlist")
	@ResponseBody
	public DtsPageResult yshlist(HttpSession session, DtsParams params) {
		User user = (User)session.getAttribute("user");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String[] cols = new String[]{"ct.id", "ct.no", "ct.company.name", "ct.area", "ct.contSmallClass.name", "ct.ycfq", "ct.isHjb", "ct.jfWtr", "ct.jfLxr", "ct.fyhj", "ct.nodeInfo", "ct.user.name", "ct.createTime", "createTime"};
		PageBean pb = params.createQuery(cols, "WorkflowLog", (query) -> {
			List<QueryBean> ret = new ArrayList<>();
			for(Map.Entry<String, String> entry : query.entrySet()) {
				if(StrUtils.isEmpty(entry.getValue())) continue;
				String key = entry.getKey();
				if("start_date".equals(key)) {
					try {
						ret.add(new QueryBean("createTime", ">=", df.parse(entry.getValue()), "start_date"));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else if("end_date".equals(key)) {
					try {
						ret.add(new QueryBean("createTime", "<=", df.parse(entry.getValue()), "end_date"));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else if("user".equals(key)) {
					ret.add(new QueryBean("ct.user.name", "like", "%" + entry.getValue() + "%"));
				} else if("ywlx".equals(key)) {
					ret.add(new QueryBean("ct.contSmallClass.id", "=", Integer.valueOf(entry.getValue())));
				}
			}
			ret.add(new QueryBean("user.id", "=", user.getId()));
			
			return ret;
		});
		PageResult pr = repo.query(pb, params.getStart(), params.getLength());
		return new DtsPageResult(params.getDraw(), pr.getTotalCount(), pr.getData());
	}
	
	//合同作废
	@RequestMapping("/cancel")
	public String cancel(Model model, HttpSession session, String no, String jfWtr, String user) {
		User audit = (User)session.getAttribute("user");
		List<Map<String, Object>> data = service.getContList1(no, jfWtr, user, null, audit, 18);
		for (Map<String, Object> map : data) {
			StringBuilder option = new StringBuilder("<a href = 'javascript:;' onclick='cancel_cont(");
			option.append(map.get("id")).append(")'>作废</a>");
			option.append("&nbsp;&nbsp;");
			option.append("<a href = 'javascript:;' onclick='return_cont(");
			option.append(map.get("id")).append(")'>驳回</a>");
			map.put("option", option.toString());
		}
		model.addAttribute("rows", data);
		model.addAttribute("url", "cancel");
		model.addAttribute("title", "合同作废");
		
		model.addAttribute("no", no);
		model.addAttribute("jfWtr", jfWtr);
		model.addAttribute("user", user);
		return "audit_list";
	}
	
	/**
	 * 合同作废申请处理
	 * @param session
	 * @param id
	 * @return
	 */
	@RequestMapping("/cancelSubmit")
	@ResponseBody
	@Transactional
    public ReturnMessage cancelSubmit(HttpSession session, int id) {
		User user = (User)session.getAttribute("user");
		Map<String, Object> ret = repo.queryOne("select new map(c.audit.id as userId, c.curNode.id as nodeId) from Contract c where c.id = ?0", id);
		if((int)ret.get("userId") !=  user.getId()) {
			return new ReturnMessage(false, "您没有作废该合同权限");
		}
		if((int)ret.get("nodeId") != 18) {
			return new ReturnMessage(false, "该合同不能被作废");
		}
		WorkflowNode nextNode = repo.find(WorkflowNode.class, 17);
		repo.queryUpdate("update Contract set curNode = ?0, nodeInfo = ?1, status = -1 where id = ?2", nextNode, nextNode.getName(), id);
		
		WorkflowLog log = new WorkflowLog();
		log.setCt(new Contract(id));
		log.setUser(user);
		log.setSpjg(1);
		log.setSpsm(nextNode.getName());
		log.setCreateTime(new Date());
		repo.persist(log);
		return new ReturnMessage(true);
	}
	
	/**
	 * 驳回合同作废申请处理
	 * @param session
	 * @param id
	 * @return
	 */
	@RequestMapping("/returnCancelSubmit")
	@ResponseBody
	@Transactional
    public ReturnMessage returnCancelSubmit(HttpSession session, int id) {
		User user = (User)session.getAttribute("user");
		Map<String, Object> ret = repo.queryOne("select new map(c.audit.id as userId, c.curNode.id as nodeId) from Contract c where c.id = ?0", id);
		if((int)ret.get("userId") !=  user.getId()) {
			return new ReturnMessage(false, "您没有作废该合同权限");
		}
		if((int)ret.get("nodeId") != 18) {
			return new ReturnMessage(false, "该合同不能被作废");
		}
		WorkflowNode nextNode = repo.find(WorkflowNode.class, 8);
		repo.queryUpdate("update Contract set curNode = ?0, nodeInfo = ?1, status = -1 where id = ?2", nextNode, "合同作废驳回", id);
		
		WorkflowLog log = new WorkflowLog();
		log.setCt(new Contract(id));
		log.setUser(user);
		log.setSpjg(1);
		log.setSpsm("合同作废驳回");
		log.setCreateTime(new Date());
		repo.persist(log);
		return new ReturnMessage(true);
	}
	
	//补录资料查看
	@RequestMapping("/blzl")
	public String blzl(HttpSession session, Model model) {
		model.addAttribute("ywlxs", repo.query("select new map(s.id as id, concat((CASE s.bigClass.area WHEN 'A' THEN '上海' WHEN 'B' THEN '苏州' WHEN 'C' THEN '成都' END), '-',  s.bigClass.name, '-', s.name) as name) from ContSmallClass s order by s.id"));
		return "blzl_list";
	}
	//补录资料列表
	@RequestMapping("/blzl/list")
	@ResponseBody
	public DtsPageResult blzlList(HttpSession session, DtsParams params) {
		User user = (User)session.getAttribute("user");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String[] cols = new String[]{"id", "no", "company.name", "area", "contSmallClass.name", "ycfq", "isHjb", "jfWtr", "jfLxr", "fyhj", "nodeInfo", "user.name", "createTime"};
		PageBean pb = params.createQuery(cols, "Contract", (query) -> {
			List<QueryBean> ret = new ArrayList<>();
			ret.add(new QueryBean("id", "in").setValue("(select cont.id from ContFile where type = 3)"));
			for(Map.Entry<String, String> entry : query.entrySet()) {
				if(StrUtils.isEmpty(entry.getValue())) continue;
				String key = entry.getKey();
				if("no".equals(key)) {
					ret.add(new QueryBean("no", "like", "%" + entry.getValue() + "%"));
				} else if("jfWtr".equals(key)) {
					ret.add(new QueryBean("jfWtr", "like", "%" + entry.getValue() + "%"));
				} else if("jfLxr".equals(key)) {
					ret.add(new QueryBean("jfLxr", "like", "%" + entry.getValue() + "%"));
				} else if("start_date".equals(key)) {
					try {
						ret.add(new QueryBean("createTime", ">=", df.parse(entry.getValue()), "start_date"));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else if("end_date".equals(key)) {
					try {
						ret.add(new QueryBean("createTime", "<=", df.parse(entry.getValue()), "end_date"));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else if("user".equals(key)) {
					ret.add(new QueryBean("user.name", "like", "%" + entry.getValue() + "%"));
				} else if("company".equals(key)) {
					String company = entry.getValue();
					if("B".equals(company)) {
						ret.add(new QueryBean("area", "=", company));	
					} else {
						ret.add(new QueryBean("area", "=", "A"));
						ret.add(new QueryBean("company.code", "=", company));
					}
					
				} else if("ywlx".equals(key)) {
					ret.add(new QueryBean("contSmallClass.id", "=", Integer.valueOf(entry.getValue())));
				}
			}
			
			return ret;
		});
		PageResult pr = repo.query(pb, params.getStart(), params.getLength());
		return new DtsPageResult(params.getDraw(), pr.getTotalCount(), pr.getData());
	}
}
